#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <vector>
#include "InetAddr.hpp"
#include "LockGuard.hpp"
#include <functional>
#include "Thread.hpp"
#include "ThreadPool.hpp"
using task_t = std::function<void()>;
class message_route
{
private:
    bool is_exists(const InetAddr &addr)
    {
        for (auto u : _online_user)
        {
            if (u == addr)
            {
                return true;
            }
        }
        return false;
    }

public:
    message_route()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    void add_user(const InetAddr &who)
    {
        LockGuard lockguard(_mutex);
        if (is_exists(who))
        {
            return;
        }
        _online_user.push_back(who);
    }
    void del_user(const InetAddr &who)
    {
        LockGuard lockguard(_mutex);
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == who)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }
    void route_helper(int sockfd, const std::string message, InetAddr who)
    {
        LockGuard lockguard(_mutex);
        // 消息转发
        for (auto u : _online_user)
        {
            std::string send_message = "\n[" + who.Ip() + " : " + std::to_string(who.Port()) + "]#" + message + "\n";
            struct sockaddr_in clientaddr = u.addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }
    void route(int sockfd, const std::string& message, InetAddr who)
    {
        // 1. 当用户首次发信息时，将用户插入在线用户中
        add_user(who);
        // 1.1 客户端退出时
        if (message == "Q" || message == "quit")
        {
            del_user(who);
        }
        // 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(&message_route::route_helper, this, sockfd, message, who);
        thread_pool<task_t>::GetInstance()->Enqueue(t);
    }
    ~message_route()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};